package com.firmail.cloud.mcenter.service.impl;

import com.firmail.mock.util.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.firmail.cloud.mcenter.service.MockCenterCloudServ;
import com.firmail.mock.center.api.vo.MockMetadata;
import com.firmail.mock.common.model.ReturnData;
import com.firmail.utils.Constants;

import java.io.IOException;

@Service
@Slf4j
public class MockCenterCloudServImpl {

    @Autowired
    private MockCenterCloudServ mockCenterCloudServ;

    public String createMock(MockMetadata data) {
        prepareData(data);
        //check the input [mockData], and deal with the data
        ReturnData<String> rd = mockCenterCloudServ.createMock(data);
        log.info("The Returned Data of The Invocation: {}", GsonUtils.toJson(rd));
        return rd == null ? Constants.CREATE_MOCK_ERR : rd.getData();
    }

    public Boolean createXPMock(MockMetadata data) throws IOException {
        prepareData(data);
        //check the input [mockData], and deal with the data
        ReturnData<?> rd = mockCenterCloudServ.createCrossPlfMock(data);
        log.info("The Returned Data of The Invocation: {}", GsonUtils.toJson(rd));
        return (Boolean) rd.getData();
    }

    private void prepareData(MockMetadata metadata) {
        if (metadata != null) {
            if (metadata.getRelativePath() != null && !metadata.getRelativePath().startsWith("/")) {
                metadata.setRelativePath("/"+metadata.getRelativePath());
            }

            metadata.setReqMethod(metadata.getReqMethod().toLowerCase());
            metadata.setDataType(metadata.getDataType().toLowerCase());
        }
    }

}
